<template>
  <div class="password">
    <el-form
      ref="form"
      class="password-form"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="新密码" prop="newPwd">
        <el-input v-model="form.newPwd" show-password />
      </el-form-item>
      <el-form-item label="确认新密码" prop="comNewPwd">
        <el-input v-model="form.comNewPwd" show-password />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit" :loading="loading"
          >更新密码</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { remakePwd } from "@/api/login";
export default {
  props: {},
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form.newPwd) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      form: {},
      rules: {
        newPwd: [{ required: true, message: "密码不能为空", trigger: "blur" }],
        comNewPwd: [{ required: true, validator: validatePass2, trigger: "blur" }],
      },
      loading: false,
    };
  },
  methods: {
    cancel() {
      this.$emit("cancel");
    },
    onSubmit() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          try {
            this.loading = true;
            const { newPwd } = this.form;
            await remakePwd({ newPwd });
            const flag = await this.$modal.confirm("修改成功是否重新登录?");
            if (!flag) return;
            await this.$store.dispatch("FedLogOut");
            this.$router.push({ path: "/login" });
          } catch (error) {
            console.error("修改密码请求错误", error);
          } finally {
            this.rest();
            this.loading = false;
          }
        }
      });
    },
    rest() {
      this.form = {
        newPwd: "",
        comNewPwd: "",
      };
      this.resetForm("form");
    },
  },
};
</script>

<style scoped lang="scss">
.password-form {
  width: 400px;
}
</style>
